/* eslint-disable react-hooks/exhaustive-deps */
import { Button, Form, Input, message } from 'antd'
import axios from 'axios';
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom';
import { API } from '../../config';
import { UserData } from '../../consts/auth';
import { isAuth } from '../../helpers/auth';
import Layout from '../core/Layout'

interface categoryValue{
    name:string
}
const AddCategory = () => {
    const [name, setName] = useState<string>('');
    const { token, user}: UserData = isAuth() as UserData;
    useEffect(() => {
        async function add(){
            try {
                const res = await axios.post<{ name: string }>(`${API}/category/create/${user._id}`,{
                    name
                },{
                    headers:{
                        Authorization:`Bearer ${token}`
                    }
                })
                message.success(`[${res.data.name}] 分类添加成功`)
            } catch (error: any) {
                message.error(error.response.data.error)
            }
        }
        if( name ){
            add();
        }
        return () => {
            
        }
    }, [name])

   

    function onFinish(params:categoryValue) {
        setName(params.name)
        form.resetFields(['name'])
    }
    const [form] = Form.useForm()
    return (
        <Layout title="添加分类" subTitle=''>
            <Form onFinish={onFinish} >
                <Form.Item label='分类名称' name='name'>
                    <Input />
                </Form.Item>
                <Form.Item>
                    <Button htmlType="submit" type='primary'>添加分类</Button>
                </Form.Item>
            </Form>
            <Button>
                <Link to='/admin/dashboard'>返回 dashboard</Link>
            </Button>
        </Layout>
    )
}

export default AddCategory
